import { history } from 'umi';
import { currentUser as queryCurrentUser, tongji } from '@/services/api';
import jsonp from 'jsonp';
import fundebug from 'fundebug-javascript';

///按需导入时需要导入一下全局css文件
///import 'react-vant/es/styles/base.css';

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';

const site_url = isDev ? 'https://test2.feinibuqu.cn' : '';

if (!isDev) {
  fundebug.notifierUrl = site_url + '/debug/?t=1';
  fundebug.apikey =
    '4fac8aa074b8db10a988d6691e7d8a262ec36771200a18d7cb926acadec712bf';
  fundebug.init({
    silentPerformance: true,
    silentPromise: true,
    silentResource: true,
    silentWebsocket: true,
    sampleRate: 1,
    filters: [
      {
        message: /^Script error\.$/,
      },
      {
        name: /^ReferenceError$/,
      },
      {
        target: {
          tagName: /^IMG$/,
          status: 'inexistence',
        },
      },
      {
        message: /WeixinJSBridge is not defined/,
      },
      {
        type: /^unhandledrejection$/,
      },
    ],
  });
}

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */

export async function getInitialState() {
  console.log('page app.jsx => getInitialState()');
  jsonp(`${site_url}/APIS/tasks/nc/shangcheng/clear.order.php`, {}, () => {});
  const fetchUserInfo = async () => {
    const res = await queryCurrentUser({ url: window.location.href });
    wx.config({
      debug: res.jssdk.debug || false, // 开启调试模式
      appId: res.jssdk.appId, // 必填，公众号的唯一标识
      timestamp: res.jssdk.timestamp, // 必填，生成签名的时间戳
      nonceStr: res.jssdk.nonceStr, // 必填，生成签名的随机串
      signature: res.jssdk.signature, // 必填，签名
      jsApiList: [
        'updateAppMessageShareData', //自定义“分享给朋友”及“分享到QQ”按钮的分享内容
        'updateTimelineShareData', //自定义“分享到朋友圈”及“分享到 QQ 空间”按钮的分享内容
        'openLocation',
        'getLocation',
        'scanQRCode',
        'chooseWXPay',
      ], // 必填，需要使用的 JS 接口列表
    });
    return {
      currentUser: res?.data,
      isLogin: res?.status,
      jssdk: res?.jssdk,
      menus: res?.menus,
      cnf: res?.cnf,
    };
  }; // 如果是登录页面，不执行
  const userdata = await fetchUserInfo();
  const share = (loc = null) => {
    const location = loc || history.location;
    wx.ready(function () {
      //需在用户可能点击分享按钮前就先调用
      wx.updateAppMessageShareData({
        title: document.title,
        desc: userdata.jssdk.desc,
        link: userdata.jssdk.link + location.pathname,
        imgUrl: userdata.jssdk.imgUrl,
        success: function () {
          // 设置成功
        },
      });
    });
    wx.ready(function () {
      //需在用户可能点击分享按钮前就先调用
      wx.updateTimelineShareData({
        title: document.title,
        link: userdata.jssdk.link + location.pathname,
        imgUrl: userdata.jssdk.imgUrl,
        success: function () {
          // 设置成功
        },
      });
    });

    let url =
      window.location.origin +
      `/APIS/nongchang/r.php?to=` +
      encodeURIComponent(window.location.href) +
      `&fromUserId=` +
      userdata?.currentUser?.uid;

    console.log(url);
    wx?.miniProgram?.getEnv(function (res) {
      if (res?.miniprogram) {
        wx?.miniProgram?.postMessage({
          data: {
            title: document.title + ' - ',
            desc: userdata?.jssdk?.desc,
            redirect: url,
          },
        });
      }
    });

    tongji({
      url: encodeURIComponent(window.location.href),
      title: document.title,
    });
  };
  const unlisten = history.listen((location, action) => {
    share(location);
  });
  share();
  console.log(
    'xxxxxxxxxxxx！！路由监听初始化，全局仅运行一次哟！！xxxxxxxxxxxxx',
  );

  return {
    fetchUserInfo,
    ...userdata,
  };
}
